<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@page pageEncoding="UTF-8" contentType="text/html; UTF-8" isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>订单管理 - 添加多商品订单</title>
    <!-- 引入jQuery库 -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <!-- 引入Font Awesome图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 基础样式 */
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; }
        .main { max-width: 1200px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .optitle { margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #eee; }
        .title { font-size: 18px; font-weight: bold; color: #333; }
        .content { background-color: #f9f9f9; padding: 20px; border-radius: 5px; margin-bottom: 20px; border: 1px solid #ddd; }
        .box { width: 100%; border-collapse: collapse; }
        .box th, .box td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; }
        .box th { background-color: #f2f2f2; font-weight: bold; }
        .field { width: 120px; font-weight: bold; }
        .buttons { margin-top: 20px; text-align: center; }
        .input-button { padding: 10px 20px; background-color: #4CAF50; color: white; border: none; border-radius: 3px; cursor: pointer; margin: 0 10px; font-size: 14px; transition: background-color 0.3s; }
        .input-button:hover { background-color: #45a049; }
        .input-button.secondary { background-color: #f44336; }
        .input-button.secondary:hover { background-color: #d32f2f; }
        .input-button.tertiary { background-color: #2196F3; }
        .input-button.tertiary:hover { background-color: #0b7dda; }
        .error { color: red; font-size: 12px; display: block; margin-top: 5px; }
        .form-control { padding: 8px; border: 1px solid #ddd; border-radius: 3px; width: 100%; box-sizing: border-box; }
        .text { padding: 8px; border: 1px solid #ddd; border-radius: 3px; width: 100%; box-sizing: border-box; }

        /* 多商品功能样式 */
        .product-section { margin: 20px 0; }
        .product-list { border-collapse: collapse; width: 100%; margin-bottom: 20px; border: 1px solid #ddd; }
        .product-list th, .product-list td { border: 1px solid #ddd; padding: 10px; text-align: left; }
        .product-list th { background-color: #f2f2f2; }
        .add-row-btn { background-color: #4CAF50; color: white; border: none; padding: 8px 15px; cursor: pointer; border-radius: 3px; margin-bottom: 10px; }
        .add-row-btn:hover { background-color: #45a049; }
        .remove-row-btn { background-color: #f44336; color: white; border: none; padding: 5px 10px; cursor: pointer; border-radius: 3px; }
        .remove-row-btn:hover { background-color: #d32f2f; }
        .total-row { font-weight: bold; background-color: #e6e6e6; }
        .required { color: red; }

        /* 动画和交互效果 */
        .product-row { transition: all 0.3s ease; }
        .product-row:hover { background-color: #f5f5f5; }
        .input-error { border: 1px solid red !important; }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .box th, .box td { display: block; width: 100%; }
            .field { width: 100%; margin-bottom: 5px; }
        }

        /* 提示框样式 */
        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: #f44336;
            color: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        /* 加载动画 */
        .spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
<div class="main">
    <div class="optitle clearfix">
        <div class="title">账单管理 > 添加多商品订单</div>
    </div>

    <form id="orderForm" name="orderForm" method="post" action="/bill/add">
        <input type="hidden" name="method" value="addMulti">
        <input type="hidden" name="orderItemsJson" id="orderItemsJson">

        <!-- 订单基本信息 -->
        <div class="content">
            <h3><i class="fas fa-info-circle"></i> 订单基本信息</h3>
            <table class="box">
                <tbody>
                <tr>
                    <td class="field">客户：<span class="required">*</span></td>
                    <td>
                        <select name="customerName" id="customerName" class="form-control">
                            <option value="">--请选择客户--</option>
                            <c:forEach items="${customers}" var="customer">
                                <option value="${customer.customerName}">${customer.customerName}</option>
                            </c:forEach>
                        </select>
                        <span id="customerIdError" class="error"></span>
                    </td>
                </tr>
                <tr>
                    <td class="field">支付方式：<span class="required">*</span></td>
                    <td>
                        <select name="paymentMethod" id="paymentMethod" class="form-control">
                            <option value="现金">现金</option>
                            <option value="微信">微信</option>
                            <option value="支付宝">支付宝</option>
                            <option value="银行卡">银行卡</option>
                        </select>
                        <span id="paymentMethodError" class="error"></span>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <!-- 商品列表区域 -->
        <div class="content product-section">
            <h3><i class="fas fa-boxes"></i> 商品列表 <span class="required">*</span></h3>
            <button type="button" id="addProductBtn" class="add-row-btn">
                <i class="fas fa-plus"></i> 添加商品
            </button>
            <table class="product-list" id="productTable">
                <thead>
                <tr>
                    <th width="25%">商品选择</th>
                    <th width="20%">商品名称</th>
                    <th width="10%">数量</th>
                    <th width="10%">单价</th>
                    <th width="15%">折扣率</th>
                    <th width="10%">单项金额</th>
                    <th width="10%">操作</th>
                </tr>
                </thead>
                <tbody id="productTableBody">
                <!-- 初始商品行 -->
                <tr class="product-row" id="row_0">
                    <td>
                        <select name="productId[]" class="product-select form-control" data-index="0">
                            <option value="">--选择商品--</option>
                            <c:forEach items="${products}" var="product">
                                <option value="${product.productID}" data-name="${product.productName}" data-price="${product.unitPrice}">
                                        ${product.productName} (${product.unitPrice}元)
                                </option>
                            </c:forEach>
                        </select>
                        <span id="productIdError_0" class="error"></span>
                    </td>
                    <td>
                        <input type="text" name="productNames[]" class="text product-name form-control" data-index="0" readonly>
                    </td>
                    <td>
                        <input type="number" name="productCount[]" class="text product-count form-control" data-index="0" value="1" min="1">
                        <span id="productCountError_0" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="unitPrice[]" class="text unit-price form-control" data-index="0" readonly step="0.01">
                    </td>
                    <td>
                        <input type="number" name="discountRate[]" class="text discount-rate form-control" data-index="0" value="0" min="0" max="1" step="0.01" title="0表示无折扣，1表示100%折扣(免费)">
                        <span id="discountRateError_0" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="lineTotal[]" class="text line-total form-control" data-index="0" readonly step="0.01">
                    </td>
                    <td>
                        <button type="button" class="remove-row-btn" disabled>
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                </tr>
                </tbody>
                <tfoot>
                <tr class="total-row">
                    <td colspan="5" class="text-right"><strong>订单总额：</strong></td>
                    <td colspan="2">
                        <span id="totalAmountDisplay" class="text-xl font-bold">0.00</span> 元
                        <input type="hidden" name="totalAmount" id="totalAmount" value="0">
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>

        <!-- 供应商与订单状态 -->
        <%--<div class="content">
            <h3><i class="fas fa-truck"></i> 订单状态</h3>
            <table class="box">
                <tbody>
                <tr>
                    <td class="field">订单状态：</td>
                    <td>
                        <select name="orderStatus" id="orderStatus" class="form-control">
                            <option value="待付款">待付款</option>
                            <option value="已付款">已付款</option>
                            <option value="已完成">已完成</option>
                            <option value="已取消">已取消</option>
                        </select>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>--%>

        <div class="buttons">
            <button type="button" id="saveOrder" class="input-button">
                <i class="fas fa-save"></i> 保存订单
            </button>
            <button type="button" id="resetForm" class="input-button secondary">
                <i class="fas fa-redo"></i> 重置
            </button>
            <button type="button" id="returnBtn" onclick="history.back(-1)" class="input-button tertiary">
                <i class="fas fa-arrow-left"></i> 返回
            </button>
        </div>
    </form>
</div>

<script type="text/javascript">
    $(document).ready(function() {
        let rowIndex = 0;
        const selectedProducts = new Set(); // 用于跟踪已选择的商品

        // 设置默认订单日期为当前时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        $("#orderDate").val(`${year}-${month}-${day}T${hours}:${minutes}`);

        // 计算单项金额 - 完全重写计算逻辑
        function calculateLineTotal($row) {
            // 获取数量、单价和折扣率
            const count = parseInt($row.find(".product-count").val()) || 0;
            const price = parseFloat($row.find(".unit-price").val()) || 0;
            const discount = parseFloat($row.find(".discount-rate").val()) || 0;

            // 计算单项金额
            const lineTotal = count * price * (1 - discount);
            
            // 设置单项金额，保留两位小数
            $row.find(".line-total").val(lineTotal.toFixed(2));
            
            return lineTotal;
        }

        // 计算订单总额
        function calculateTotalAmount() {
            let total = 0;
            $(".product-row").each(function() {
                const lineTotal = calculateLineTotal($(this));
                total += lineTotal;
            });

            $("#totalAmount").val(total.toFixed(2));
            $("#totalAmountDisplay").text(total.toFixed(2));
        }

        // 初始化商品选择事件（使用事件委托）
        $("#productTableBody").on("change", ".product-select", function() {
            const $row = $(this).closest(".product-row");
            const productId = $(this).val();
            const selectedOption = $(this).find("option:selected");

            // 检查商品是否已被选择
            if (productId && selectedProducts.has(productId) && !($row.data("current-product-id") === productId)) {
                alert("该商品已经被选择，请选择其他商品！");
                $(this).val("");
                return;
            }

            // 移除旧的商品ID
            if ($row.data("current-product-id")) {
                selectedProducts.delete($row.data("current-product-id"));
            }

            if (productId) {
                // 添加新的商品ID到已选择集合
                selectedProducts.add(productId);
                $row.data("current-product-id", productId);

                const productName = selectedOption.data("name");
                const unitPrice = selectedOption.data("price");

                $row.find(".product-name").val(productName);
                $row.find(".unit-price").val(unitPrice);

                // 计算单项金额和总额
                calculateTotalAmount();
            } else {
                $row.find(".product-name").val("");
                $row.find(".unit-price").val("");
                $row.find(".line-total").val("0.00");
                $row.removeData("current-product-id");
                calculateTotalAmount();
            }
        });

        // 数量和折扣率变化事件（使用事件委托）
        $("#productTableBody").on("input", ".product-count, .discount-rate", function() {
            const $input = $(this);
            const $row = $input.closest(".product-row");
            
            if ($input.hasClass("product-count")) {
                // 立即验证并纠正数量
                let value = parseInt($input.val()) || 0;
                if (value <= 0) {
                    value = 1;
                }
                $input.val(value);
            } else if ($input.hasClass("discount-rate")) {
                // 立即验证并纠正折扣率
                let value = parseFloat($input.val()) || 0;
                value = Math.max(0, Math.min(1, value));
                $input.val(value.toFixed(2));
            }

            // 重新计算总额
            calculateTotalAmount();
        });

        // 删除商品行 - 更新处理
        $("#productTableBody").on("click", ".remove-row-btn", function() {
            const $row = $(this).closest(".product-row");
            const productId = $row.data("current-product-id");
            if (productId) {
                selectedProducts.delete(productId);
            }
            $row.remove();
            updateRemoveButtonStates();
            calculateTotalAmount();
        });

        // 添加商品行时的处理
        $("#addProductBtn").click(function() {
            rowIndex++;
            const newRow = `
                <tr class="product-row" id="row_${rowIndex}">
                    <td>
                        <select name="productId[]" class="product-select form-control" data-index="${rowIndex}">
                            <option value="">--选择商品--</option>
                            <c:forEach items="${products}" var="product">
                                <option value="${product.productID}" data-name="${product.productName}" data-price="${product.unitPrice}">
                                    ${product.productName} (${product.unitPrice}元)
                                </option>
                            </c:forEach>
                        </select>
                        <span id="productIdError_${rowIndex}" class="error"></span>
                    </td>
                    <td>
                        <input type="text" name="productNames[]" class="text product-name form-control" readonly>
                    </td>
                    <td>
                        <input type="number" name="productCount[]" class="text product-count form-control" value="1" min="1">
                        <span id="productCountError_${rowIndex}" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="unitPrice[]" class="text unit-price form-control" readonly step="0.01">
                    </td>
                    <td>
                        <input type="number" name="discountRate[]" class="text discount-rate form-control" value="0" min="0" max="1" step="0.01" title="0表示无折扣，1表示100%折扣(免费)">
                        <span id="discountRateError_${rowIndex}" class="error"></span>
                    </td>
                    <td>
                        <input type="number" name="lineTotal[]" class="text line-total form-control" readonly step="0.01">
                    </td>
                    <td>
                        <button type="button" class="remove-row-btn">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                </tr>
            `;

            $("#productTableBody").append(newRow);
            updateRemoveButtonStates();
            calculateTotalAmount();

            // 滚动到新添加的行
            $('html, body').animate({
                scrollTop: $(`#row_${rowIndex}`).offset().top - 100
            }, 500);
        });

        // 更新删除按钮状态
        function updateRemoveButtonStates() {
            const rows = $(".product-row");
            if (rows.length <= 1) {
                rows.find(".remove-row-btn").attr("disabled", true);
            } else {
                rows.find(".remove-row-btn").attr("disabled", false);
            }
        }

        // 表单提交前的最终验证
        $("#saveOrder").click(function() {
            let isValid = true;
            let errorMessage = "";

            // 验证是否至少有一个商品
            if ($(".product-row").length === 0) {
                errorMessage += "请至少添加一个商品\n";
                isValid = false;
            }

            // 验证基本信息
            if ($("#customerId").val() === "") {
                errorMessage += "请选择客户\n";
                $("#customerId").addClass("input-error");
                isValid = false;
            }

            if ($("#supplierId").val() === "") {
                errorMessage += "请选择供应商\n";
                $("#supplierId").addClass("input-error");
                isValid = false;
            }

            if ($("#orderDate").val() === "") {
                errorMessage += "请选择订单日期\n";
                $("#orderDate").addClass("input-error");
                isValid = false;
            }

            // 验证商品列表
            $(".product-row").each(function(index) {
                const $row = $(this);
                if ($row.find(".product-select").val() === "") {
                    errorMessage += `第 ${index + 1} 行：请选择商品\n`;
                    $row.find(".product-select").addClass("input-error");
                    isValid = false;
                }
            });

            if (!isValid) {
                alert("表单验证失败：\n" + errorMessage);
                return;
            }

            // 最终确认
            if (confirm("确认提交订单吗？")) {
                // 收集商品信息
                const orderItemViews = [];
                $(".product-row").each(function() {
                    const $row = $(this);
                    orderItemViews.push({
                        productId: $row.find(".product-select").val(),
                        productName: $row.find(".product-name").val(),
                        productCount: parseInt($row.find(".product-count").val()),
                        unitPrice: parseFloat($row.find(".unit-price").val()),
                        discountRate: parseFloat($row.find(".discount-rate").val()),
                        lineTotal: parseFloat($row.find(".line-total").val())
                    });
                });

                $("#orderItemsJson").val(JSON.stringify(orderItemViews));
                $("#orderForm").submit();
            }
        });

        // 重置表单 - 更新处理
        $("#resetForm").click(function() {
            if (confirm("确定要重置表单吗？所有已输入的数据将被清除。")) {
                $("#orderForm")[0].reset();
                $(".error").text("");
                $(".input-error").removeClass("input-error");
                selectedProducts.clear(); // 清除已选择的商品记录
                
                // 重置订单日期为当前时间
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const day = String(now.getDate()).padStart(2, '0');
                const hours = String(now.getHours()).padStart(2, '0');
                const minutes = String(now.getMinutes()).padStart(2, '0');
                $("#orderDate").val(`${year}-${month}-${day}T${hours}:${minutes}`);

                // 重置商品表格到初始状态
                $("#productTableBody").html(`
                    <tr class="product-row" id="row_0">
                        <td>
                            <select name="productId[]" class="product-select form-control" data-index="0">
                                <option value="">--选择商品--</option>
                                <c:forEach items="${products}" var="product">
                                    <option value="${product.productID}" data-name="${product.productName}" data-price="${product.unitPrice}">
                                        ${product.productName} (${product.unitPrice}元)
                                    </option>
                                </c:forEach>
                            </select>
                            <span id="productIdError_0" class="error"></span>
                        </td>
                        <td>
                            <input type="text" name="productName[]" class="text product-name form-control" data-index="0" readonly>
                        </td>
                        <td>
                            <input type="number" name="productCount[]" class="text product-count form-control" data-index="0" value="1" min="1">
                            <span id="productCountError_0" class="error"></span>
                        </td>
                        <td>
                            <input type="number" name="unitPrice[]" class="text unit-price form-control" data-index="0" readonly step="0.01">
                        </td>
                        <td>
                            <input type="number" name="discountRate[]" class="text discount-rate form-control" data-index="0" value="0" min="0" max="1" step="0.01" title="0表示无折扣，1表示100%折扣(免费)">
                            <span id="discountRateError_0" class="error"></span>
                        </td>
                        <td>
                            <input type="number" name="lineTotal[]" class="text line-total form-control" data-index="0" readonly step="0.01">
                        </td>
                        <td>
                            <button type="button" class="remove-row-btn" disabled>
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </td>
                    </tr>
                `);
                rowIndex = 0;
                calculateTotalAmount();
            }
        });
    });
</script>
</body>
</html>